package com.hua.yuan.live;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hua.yuan.base.BaseAppActivity;
import com.hua.yuan.base.Constents;
import com.hua.yuan.dialog.ConfirmCancelDialog;
import com.hua.yuan.live.adapter.PublicChatAdapter;
import com.hua.yuan.live.dialog.RedRackageDialog;
import com.hua.yuan.live.repertory.cloud_data.loader.LiveAttentationLoader;
import com.hua.yuan.live.repertory.cloud_data.loader.LiveGiveMoneyLoader;
import com.hua.yuan.live.repertory.cloud_data.loader.LiveRoomLoader;
import com.hua.yuan.live.repertory.cloud_data.res.GroupChat;
import com.hua.yuan.live.repertory.cloud_data.res.LivePlayBean;
import com.hua.yuan.live.repertory.cloud_data.res.LivePlayComband;
import com.hua.yuan.live.repertory.cloud_data.res.ResultMsg;
import com.hua.yuan.live.repertory.cloud_data.res.UserBean;
import com.hua.yuan.rtcroom.RTCRoom;
import com.hua.yuan.rtcroom.sdk.im.IMMessageMgr;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.util.List;

import cm.hua.yuan.common.utils.PreferenceUtils;

/**
 * @author richsjeson
 * 正在直播的页面
 */
public class LiveRoomActivity extends BaseAppActivity implements LoaderManager.LoaderCallbacks<LivePlayComband>,
        View.OnClickListener,
        IMMessageMgr.Callback,
        LiveAttentationLoader.onAttentationCallback,
        LiveGiveMoneyLoader.OnGivePlayCallback,
        RedRackageDialog.OnRedPackageListener,
        ConfirmCancelDialog.OnConfirmListener,
        IMMessageMgr.IMMessageListener {

    private LiveRoomLoader mLoader;
    private final int resutltCode = 1001;
    private TXCloudVideoView mPlayView;
    private TXLivePlayer livePlayer;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO};
    private boolean checkedPermission;
    private ImageView ivRedPackage;
    private ImageView ivClose;
    private TextView tvAnchorName;
    private TextView tvViewer;
    private TextView tvRoomNo;
    private TextView tvSendMsg;
    private ImageView ivReservation;
    /**
     * 当前用户的代币
     */
    private int mMoney;
    /**
     * 主播iD
     */
    private int anchorId;
    /**
     * 主播昵称
     */
    private String anchorNickName;

    /**
     * 是否是关注的
     */
    private int isAttentaion;

    private ImageView ivAttentaion;

    private String mToken;
    /**
     * 弹幕聊天室的群主ID
     */
    private String mChatGroupId;
    /**
     * 赠送红包
     */
    private ImageView mBtnSendPackage;

    private ImageView mBtnPrivateRoom;

    private ConfirmCancelDialog mConfigDialog;

    private boolean mStateEnable;

    private RedRackageDialog redPackageDialog;

    private Integer   mSendMoney ;

    private final static String TAG = LiveRoomActivity.class.getName();

    private ListView lsvRedPackage;

    private PublicChatAdapter mAdapter;

    private TextView edtSendMsg;

    private RTCRoom mRtcRoom;

    private String mPlayUrl;

    @Override
    protected int initLayoutId() {
        mLoader = new LiveRoomLoader();
        checkPermission();
        return R.layout.activity_live_room;
    }

    @Override
    protected void initView() {
        mPlayView = findView(R.id.video_liveroom);
        ivClose = findView(R.id.iv_closeicon_live_room);
        tvAnchorName = findView(R.id.tv_anchor_name_live_room);
        tvViewer = findView(R.id.tv_viewer_live_room);
        tvRoomNo = findView(R.id.tv_anchor_roomno_live_room);
        tvSendMsg = findView(R.id.tv_send_message_live_room);
        ivReservation = findView(R.id.btn_reservation_live_room);
        ivAttentaion = findView(R.id.iv_attention_live_room);
        mBtnSendPackage = findView(R.id.iv_send_package);
        mBtnPrivateRoom = findView(R.id.btn_private_live_room);
        mConfigDialog =   ConfirmCancelDialog.create(getSupportFragmentManager());
        mConfigDialog.setOnConfirmListener(this);
        //视频布局
        livePlayer = new TXLivePlayer(this);
        livePlayer.setPlayerView(mPlayView);
        livePlayer.setConfig(new TXLivePlayConfig());
        livePlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
    }

    private void initData() {
        mRtcRoom=LiveModule.getRtcRoom(this);
        int viewer = getIntent().getIntExtra(LiveModule.INTENT_ANCHOR_ONLINE, 0);
        tvViewer.setText(String.valueOf(viewer));
        tvRoomNo.setText(String.valueOf(anchorId));
        mToken = PreferenceUtils.getString(Constents.TOKEN);
        anchorId = getIntent().getIntExtra(LiveModule.INTENT_ANCHOR_ID, 0);
        anchorNickName = getIntent().getStringExtra(LiveModule.INTENT_ANCHOR_NICK_NAME);
        mChatGroupId = getIntent().getStringExtra(LiveModule.INTENT_GROUP_ID) == null ?
                "" : getIntent().getStringExtra(LiveModule.INTENT_GROUP_ID);
        mLoader.requestRoomLife(mToken.trim(), anchorId, this);

        edtSendMsg=findView(R.id.edt_input_content_live_room);

        if (!TextUtils.isEmpty(anchorNickName)) {
            tvAnchorName.setText(anchorNickName);
        }

        redPackageDialog = new RedRackageDialog(this);
        redPackageDialog.setOnRedPackageListener(this);
        mRtcRoom.getIMMessageMgr().setIMMessageListener(this);
        lsvRedPackage = findViewById(R.id.lsv_red_package_live_roomm);
        mAdapter = new PublicChatAdapter(this);
        lsvRedPackage.setAdapter(mAdapter);
        Toast.makeText(getApplicationContext(), "初始化成功", Toast.LENGTH_SHORT).show();
        mRtcRoom.getIMMessageMgr().jionGroup(mChatGroupId, new IMMessageMgr.Callback() {
            @Override
            public void onError(int code, String errInfo) {

            }

            @Override
            public void onSuccess(Object... args) {

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(livePlayer==null || mPlayUrl==null){
            return;
        }
        if(!livePlayer.isPlaying()){
            livePlayer.startPlay(mPlayUrl, TXLivePlayer.PLAY_TYPE_LIVE_FLV);
        }
    }

    /**
     * 添加监听
     */
    private void addListener() {
        ivClose.setOnClickListener(this);
        tvSendMsg.setOnClickListener(this);
        ivReservation.setOnClickListener(this);
        ivAttentaion.setOnClickListener(this);
        mBtnSendPackage.setOnClickListener(this);
        mBtnPrivateRoom.setOnClickListener(this);
    }

    @Override
    protected void initNet() {

        initData();
        addListener();
    }

    @NonNull
    @Override
    public Loader<LivePlayComband> onCreateLoader(int id, @Nullable Bundle args) {
        return null;
    }

    @Override
    public void onLoadFinished(@NonNull Loader<LivePlayComband> loader, final LivePlayComband data) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (data == null) {
                    return;
                }

                LivePlayBean playBean = data.getLivePlayBean();

                if (playBean == null) {
                    return;
                }
                List<String> pushUrl = playBean.getPlayUrl();

                String playUrl = "";

                for (int i = 0; i < pushUrl.size(); i++) {


                    if (pushUrl.get(i).contains(".flv")) {
                        playUrl = pushUrl.get(i);
                        break;
                    }
                }
                mPlayView.setVisibility(View.VISIBLE);
                mPlayUrl=playUrl;
                livePlayer.startPlay(playUrl, TXLivePlayer.PLAY_TYPE_LIVE_FLV);
                //已获取到当前用户的代币了
                mMoney = (data.getMoneyBean().getErrorNo() != 0 ? 0 : data.getMoneyBean().getMoney());
            }
        });

    }

    @Override
    public void onLoaderReset(@NonNull Loader<LivePlayComband> loader) {

    }

    /**
     * 检查是否打开摄像头的权限
     */
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            //进入到这里代表没有权限.
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
                //已经禁止提示了
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.live_weight), Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } else {
            checkedPermission = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户同意授权
                    checkedPermission = true;
                }
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
    }

    @Override
    public void onClick(View v) {
        if (R.id.iv_send_package == v.getId()) {
            if (!redPackageDialog.isShowing()) {
                int[] location = new int[2];
                v.getLocationOnScreen(location);
                redPackageDialog.showUp(mBtnSendPackage);
                redPackageDialog.setMoney(this,String.valueOf(mMoney));
            } else {
                redPackageDialog.dismiss();
            }
        } else if (R.id.iv_closeicon_live_room == v.getId()) {
            onBackPressed();
        } else if (R.id.tv_send_message_live_room == v.getId()) {
            if(!TextUtils.isEmpty(edtSendMsg.getText())) {
                sendChatGroupMsg(edtSendMsg.getText().toString(),1);
            }
        } else if (R.id.btn_reservation_live_room == v.getId()) {
            jumpActivity(LiveReservationActivity.class);
        } else if (R.id.btn_private_live_room == v.getId()) {
            jumpActivity(PrivateChatActivity.class);
        } else if (R.id.iv_attention_live_room == v.getId()) {
            LiveAttentationLoader.attentation(mToken, anchorId, isAttentaion, this);
        }
    }

    /**
     * 赠送代币
     */
    @SuppressLint("StringFormatMatches")
    private void sendRedPackage() {

        if (!isFinishing()) {
            if (mConfigDialog.isAdded()) {
                mConfigDialog.dismiss();
            } else {
                mConfigDialog.setMoney(String.valueOf(mSendMoney),getApplicationContext());
                mConfigDialog.show();
            }
        }
    }

    private void jumpActivity(Class pActivity) {
        stopPlay();
        Intent intent = new Intent();
        intent.setClass(this, pActivity);
        intent.putExtra(LiveModule.INTENT_ANCHOR_ID, anchorId);
        intent.putExtra(LiveModule.INTENT_USER_MONEY, mMoney);
        intent.putExtra(LiveModule.INTENT_ANCHOR_RTC_USER_ID, getIntent().getStringExtra(LiveModule.INTENT_ANCHOR_RTC_USER_ID));
        intent.putExtra(LiveModule.INTENT_ANCHOR_NICK_NAME, getIntent().getStringExtra(LiveModule.INTENT_ANCHOR_NICK_NAME));
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivity(intent);
        }
    }

    /**
     * 发送弹幕信息
     */
    private void sendChatGroupMsg(final String pMessage,int type) {

        final String userInfo = PreferenceUtils.getString(Constents.USER_INFO);
        if(TextUtils.isEmpty(userInfo)){
            return;
        }
        UserBean userBean=JSON.parseObject(userInfo,UserBean.class);
        String nickName="";
        String mobilePhone=userBean.getMobilePhone();
        if(TextUtils.isEmpty(userBean.getNickName())){

            if(!TextUtils.isEmpty(mobilePhone)){
                nickName=mobilePhone.substring(mobilePhone.length()-3,mobilePhone.length());
                nickName=String.format("***%s",nickName);
            }
        }
        final GroupChat groupChat = new GroupChat();
        groupChat.setContent(pMessage);
        groupChat.setUserName(nickName);
        groupChat.setType(type);
        groupChat.setRoom(mChatGroupId);
        String sendMsgProtocol= JSONObject.toJSONString(groupChat);
        LiveModule.getRtcRoom(this).getIMMessageMgr().sendGroupTextMessage(null, null, sendMsgProtocol, new IMMessageMgr.Callback() {
            @Override
            public void onError(int code, final String errInfo) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), errInfo, Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onSuccess(Object... args) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
                        if (!mAdapter.getData().contains(groupChat)) {
                            mAdapter.getData().add(groupChat);
                            mAdapter.notifyDataSetChanged();
                            lsvRedPackage.scrollTo(0,0);
                            edtSendMsg.setText("");
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onBackPressed() {
        LiveModule.getRtcRoom(this).getIMMessageMgr().quitGroup(mChatGroupId, new IMMessageMgr.Callback() {
            @Override
            public void onError(int code, String errInfo) {

            }

            @Override
            public void onSuccess(Object... args) {

            }
        });
        setResult(resutltCode);
        stopPlay();
        finish();
    }

    @Override
    protected void onStop() {
        stopPlay();
        super.onStop();
    }

    @Override
    public void onError(int code, final String errInfo) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), errInfo, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onSuccess(Object... args) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    @Override
    public void attentation(Integer isSuccess) {
        if (isSuccess == 0) {
            Toast.makeText(getApplicationContext(), "关注成功", Toast.LENGTH_SHORT).show();
            isAttentaion = (isAttentaion == 0 ? 1 : 0);
        } else {
            Toast.makeText(getApplicationContext(), "关注失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void playVideoStatus(ResultMsg res) {

        if (res.getErrNo() == 0) {
            Toast.makeText(getApplicationContext(), "赠送成功", Toast.LENGTH_SHORT).show();
            String sendMoneyMsg = String.format("赠送主播 %d 代币", mSendMoney);
            sendChatGroupMsg(sendMoneyMsg,2);
            mMoney=mMoney-mSendMoney;
        } else {
            Toast.makeText(getApplicationContext(), res.getErrMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailure(Throwable e) {

    }

//    @Override
    public void onConfirm(View v) {
        //目前暂时定义为5个代币

        if(mMoney>mSendMoney){
            redPackageDialog.dismiss();
            LiveGiveMoneyLoader.requestGiveMoney(mToken, anchorId,String.valueOf(mSendMoney), this);
            return;
        }
        Intent intent = new Intent();
        intent.setClassName(this, "com.hua.yuan.ui.MoneyBagActivity");
        intent.putExtra("buyMoney",String.valueOf(mSendMoney));
        intent.putExtra("movieId",String.valueOf(anchorId));
        intent.putExtra("isTuji",false);
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivity(intent);
            return;
        }

    }

    /**
     * 停止推流
     */
    private void stopPlay() {
        if (livePlayer.isPlaying()) {
            livePlayer.stopPlay(true);
        }
    }

    @Override
    public void sendPackage(View view, Integer money) {
        this.mSendMoney = money;
        sendRedPackage();
    }

    @Override
    public void onConnected() {

    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onPusherChanged() {

    }

    @Override
    public void onGroupTextMessage(String groupID, String senderID, String userName, String headPic, final String message) {
        Log.i(TAG, "接收到消息了：" + message);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                GroupChat groupChat = (GroupChat) JSON.parseObject(message,GroupChat.class);
                if(groupChat==null){
                    return;
                }
                if (!mAdapter.getData().contains(groupChat)) {
                    mAdapter.getData().add(groupChat);
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    @Override
    public void onGroupCustomMessage(String groupID, String senderID, String message) {

    }

    @Override
    public void onC2CCustomMessage(String sendID, String cmd, String message) {

    }

    @Override
    public void onGroupDestroyed(String groupID) {

    }

    @Override
    public void onDebugLog(String log) {

    }
}
